function [edges, dvals] = slnn2edges(nnidx, dists)
%SLNN2EDGES Converts the nearest neighbor indices to edges
%
% [ Syntax ]
%   - edges = slnn2edges(nnidx)
%   - [edges, dvals] = slnn2edges(nnidx, dists)
%
% [ Arguments ]
%   - nnidx:        the matrix of k nearest neighbor indices (k x n)
%   - dists:        the distance matrix corresponding to nnidx (k x n)
%   - edges:        the ne x 2 matrix representing the edge set
%   - dvals:        the distane value vector corresponding to edges (ne x 1)
%
% [ Description ]
%   - edges = slnn2edges(nnidx) converts the matrix of neighbor indices
%     to an edge set, which contains the edges connecting each node to its
%     neighbors.
%
%     Suppose there are ne edges, then the output edges would be an ne x 2 
%     matrix with each row giving the indices of the source node and the
%     target node of an edge.
%
%   - [edges, dvals] = slnn2edges(nnidx, dists) additionally returns the
%     distance value vector, in which dvals(i) refers to the distance
%     metric value corresponding to the edge edges(i, :).
%
% [ History ]
%   - Created by Dahua Lin, on Jul 7, 2007
%

assert(isnumeric(nnidx) && ndims(nnidx) == 2, ...
    'sltoolbox:slnn2edges:invalidarg', 'nnidx should be a real matrix');

srcidx = repmat(1:size(nnidx, 2), size(nnidx, 1), 1);

is_edge = nnidx > 0;
edges = [srcidx(is_edge), nnidx(is_edge)];

if nargin >= 2 && nargout >= 2
    dvals = dists(is_edge);
end



